import React, { Component } from 'react';
import { View } from 'react-native';
import { Router, Actions } from 'react-native-router-flux';
import _ from 'lodash';
import { observer } from 'mobx-react';
import { AsyncStorage } from 'react-native';
import Storage from 'react-native-storage';
import * as wechat from 'react-native-wechat';
import user from './src/common/models/user';
import * as services from './src/modules/customer/services';
import { get } from './src/utils/request';
import { isIphoneX } from './src/utils';

import PKG from './package.json';


Date.prototype.format = function (fmt) { //author: meizz 
  const o = {
    "M+": this.getMonth() + 1, //月份 
    "D+": this.getDate(), //日 
    "H+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  }
  return fmt;
}

global.appInfo = {
  name: PKG.name,
  version: PKG.version
};
storage = new Storage({
  size: 1000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24 * 7,
  enableCache: true,
  sync: {
    ...services,
  }
});
global.storage = storage;
wechat.registerApp('wx4d7943b028ad3a61');

const checkVersion = (currentVer) => {
  get('v1/common/version').then(newVersion => {
    if (newVersion) {
      const curVer = currentVer.split('.');
      const newVer = newVersion.split('.');
      for (let i = 0; i < newVer.length; i++) {
        if (newVer[i] > curVer[i]) {
          // TODO
          break;
        }
      }
    }
  }).catch()
}

@observer
class App extends Component {
  componentDidMount() {
    storage
      .load({
        key: 'userInfo'
      })
      .then(userInfo => {
        user.saveUserInfo(userInfo);
        Actions.replace('main');
      })
      .catch(e => {
        Actions.reset('start');
      });
    checkVersion(global.appInfo.version);
  }
  render() {
    return (
      <View
        style={{ paddingBottom: isIphoneX() ? 24 : 0, backgroundColor: '#fff', flex: 1 }}
      >
        <Router sceneStyle={{ shadowRadius: 0, shadowOffset: { width: 0, height: 0 } }}>{require('./src')}</Router>
      </View>
    )
  }
}
export default App;
